import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'aes_utils.dart';

class AESDemoPage extends StatefulWidget {
  @override
  _AESDemoPageState createState() => _AESDemoPageState();
}

class _AESDemoPageState extends State<AESDemoPage> {
  final _keyController = TextEditingController(text: 'comic_us_en_1234');
  final _inputController = TextEditingController(text: 'Hello, Flutter AES!');
  final _outputController = TextEditingController();

  bool _isEncrypting = true; // true: 加密模式, false: 解密模式
  String _statusMessage = '';

  @override
  void dispose() {
    _keyController.dispose();
    _inputController.dispose();
    _outputController.dispose();
    super.dispose();
  }

  void _performOperation() {
    final key = _keyController.text.trim();
    final input = _inputController.text.trim();

    if (key.isEmpty) {
      _showMessage('请输入密钥', isError: true);
      return;
    }

    if (input.isEmpty) {
      _showMessage('请输入要${_isEncrypting ? "加密" : "解密"}的内容', isError: true);
      return;
    }

    try {
      String result;
      if (_isEncrypting) {
        result = AESUtil.encryptECB(input);
        _showMessage('加密成功');
      } else {
        result = AESUtil.decryptECB(input);
        _showMessage('解密成功');
      }

      setState(() {
        _outputController.text = result;
      });
    } catch (e) {
      _showMessage(e.toString(), isError: true);
    }
  }

  void _showMessage(String message, {bool isError = false}) {
    setState(() {
      _statusMessage = message;
    });

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _generateRandomKey() {
    // final randomKey = AESUtil.generateRandomKey();
    // setState(() {
    //   _keyController.text = randomKey;
    // });
    // _showMessage('已生成随机密钥');
  }

  void _copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
    _showMessage('已复制到剪贴板');
  }

  void _swapInputOutput() {
    final temp = _inputController.text;
    setState(() {
      _inputController.text = _outputController.text;
      _outputController.text = temp;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AES加密解密Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 模式切换
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text(
                      '操作模式',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    SizedBox(height: 8),
                    SegmentedButton<bool>(
                      segments: [
                        ButtonSegment(
                          value: true,
                          label: Text('加密'),
                          icon: Icon(Icons.lock),
                        ),
                        ButtonSegment(
                          value: false,
                          label: Text('解密'),
                          icon: Icon(Icons.lock_open),
                        ),
                      ],
                      selected: {_isEncrypting},
                      onSelectionChanged: (Set<bool> selection) {
                        setState(() {
                          _isEncrypting = selection.first;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 密钥输入
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            '加密密钥 (AES-256 ECB模式)',
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                        ),
                        TextButton.icon(
                          onPressed: _generateRandomKey,
                          icon: Icon(Icons.refresh),
                          label: Text('随机生成'),
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    TextField(
                      controller: _keyController,
                      decoration: InputDecoration(
                        hintText: '请输入密钥',
                        border: OutlineInputBorder(),
                        suffixIcon: IconButton(
                          icon: Icon(Icons.copy),
                          onPressed: () =>
                              _copyToClipboard(_keyController.text),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 输入文本
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            _isEncrypting ? '要加密的明文' : '要解密的密文',
                            style: Theme.of(context).textTheme.titleMedium,
                          ),
                        ),
                        IconButton(
                          icon: Icon(Icons.swap_vert),
                          onPressed: _swapInputOutput,
                          tooltip: '交换输入输出',
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    TextField(
                      controller: _inputController,
                      maxLines: 4,
                      decoration: InputDecoration(
                        hintText: _isEncrypting ? '请输入要加密的文本' : '请输入要解密的密文',
                        border: OutlineInputBorder(),
                        suffixIcon: IconButton(
                          icon: Icon(Icons.copy),
                          onPressed: () =>
                              _copyToClipboard(_inputController.text),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 操作按钮
            ElevatedButton.icon(
              onPressed: _performOperation,
              icon: Icon(_isEncrypting ? Icons.lock : Icons.lock_open),
              label: Text(_isEncrypting ? '开始加密' : '开始解密'),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 16),
                textStyle: TextStyle(fontSize: 16),
              ),
            ),

            SizedBox(height: 16),

            // 输出结果
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _isEncrypting ? '加密结果 (Base64)' : '解密结果',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    SizedBox(height: 8),
                    TextField(
                      controller: _outputController,
                      maxLines: 4,
                      readOnly: true,
                      decoration: InputDecoration(
                        hintText: '结果将显示在这里',
                        border: OutlineInputBorder(),
                        suffixIcon: IconButton(
                          icon: Icon(Icons.copy),
                          onPressed: () =>
                              _copyToClipboard(_outputController.text),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 状态信息
            if (_statusMessage.isNotEmpty)
              Card(
                color: Colors.blue.shade50,
                child: Padding(
                  padding: EdgeInsets.all(12.0),
                  child: Row(
                    children: [
                      Icon(Icons.info, color: Colors.blue),
                      SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          _statusMessage,
                          style: TextStyle(color: Colors.blue.shade700),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

            SizedBox(height: 16),

            // 说明信息
            Card(
              color: Colors.grey.shade50,
              child: Padding(
                padding: EdgeInsets.all(12.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '使用说明：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 4),
                    Text('• 使用AES-256 ECB模式加密，只需要密钥，不需要IV'),
                    Text('• 密钥会自动填充或截断到32字节'),
                    Text('• 加密结果以Base64格式显示'),
                    Text('• 可以点击复制按钮复制内容到剪贴板'),
                    Text('• 可以使用交换按钮快速交换输入输出内容'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
